package com.huika.renrench.control.my.bank.activity;


import java.util.ArrayList;

import android.app.Dialog;
import android.content.Intent;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.AccountPropertyBean;
import com.huika.renrench.support.bean.BankCardBean;
import com.huika.renrench.view.TitleBarHelper;

/**
 * 
 * @description：添加银行卡和查看银行卡信息
 * @author zc
 * @date 2015年6月2日 上午11:21:59
 */
public class BankInfoActivity extends BaseAct implements Listener<RequestResult<ArrayList<BankCardBean>>> {

	private TextView name_detail;
	private TextView bank_name_detail;
	private TextView card_number_detail_tv;
	private TextView open_card_address_detail_tv;
	private EditText card_number_detail_et;
	private EditText open_card_address_detail_et;
	private Button confirm;
	private int flag = -1;//标志位0添加银行卡还是1查看银行卡
	private BankCardBean bankCardBean;
	public static ArrayList<BankCardBean> bankList = new ArrayList<BankCardBean>();
	private BankCardBean chooseBean;//选择的bean
	private String userId;
	private TextView open_card_address;
	private Dialog dialog ;
	private double totalAccount;
	private AccountPropertyBean accountPropertyBean;
	private TextView propmt_detail;
	private TextView propmt;
	
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_add_bank_card);
		
	}
	
	@Override
	protected void initData() {
		super.initData();
		Intent intent = getIntent();
		flag = intent.getIntExtra("flag", -1);
		if(flag == 1) {
			bankCardBean = (BankCardBean) intent.getSerializableExtra("bankCardBean");
		}
		TitleBarHelper barHelper = new TitleBarHelper(this, -1);
		barHelper.setLeftMsg("返回");
		if(flag == 0) {
			barHelper.setTitleMsg("添加银行卡");
		} else {
			barHelper.setTitleMsg("查看银行卡");
		}
		userId = GlobalApp.getInstance().getUserId();
	}
	
	@Override
	protected void initWidget() {
		super.initWidget();
		name_detail = (TextView) findViewById(R.id.name_detail);
		bank_name_detail = (TextView) findViewById(R.id.bank_name_detail);
		card_number_detail_tv = (TextView) findViewById(R.id.card_number_detail_tv);
		open_card_address_detail_tv = (TextView) findViewById(R.id.open_card_address_detail_tv);
		card_number_detail_et = (EditText) findViewById(R.id.card_number_detail_et);
		open_card_address_detail_et = (EditText) findViewById(R.id.open_card_address_detail_et);
		open_card_address = (TextView) findViewById(R.id.open_card_address);
		propmt_detail = (TextView) findViewById(R.id.propmt_detail);
		confirm = (Button) findViewById(R.id.confirm);
		propmt = (TextView) findViewById(R.id.propmt);
		
		getTip(userId);
		if(flag == 1) {
			confirm.setText("删除");
			open_card_address.setVisibility(View.GONE);
			bank_name_detail.setText(bankCardBean.getBankName());
			open_card_address_detail_et.setVisibility(View.GONE);
			card_number_detail_et.setVisibility(View.GONE);
			card_number_detail_tv.setVisibility(View.VISIBLE);
			card_number_detail_tv.setText(getHideIdCard(bankCardBean.getCardNumber()));
			open_card_address_detail_tv.setText(bankCardBean.getSubbranchBank());
			bank_name_detail.setCompoundDrawables(null, null, null, null);
		} else {
			name_detail.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
			bank_name_detail.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
		}
		name_detail.setText(getHideRealName(GlobalApp.userModel.getRealName()));
		confirm.setOnClickListener(this);
		if(flag == 0) {
			getBankList(userId);
			bank_name_detail.setOnClickListener(this);
		}
		
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
			case R.id.confirm:
				if(flag == 1) {
					getDataFromNet(userId);
//					warning();
//					deleteBankCard(userId, bankCardBean.getCardId());
				} else {
					checkInput();
					
				}
				break;
			case R.id.bank_name_detail:
				Intent intent = new Intent(this, BankCardListActivity.class);
				startActivityForResult(intent, 100);
				break;
		}
	}
	
	private void getTip(String userId) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("tipType", "bankTip");
		FormResultRequest<Object> getResultRequest = new FormResultRequest<Object>(
				UrlConstants.GETTIP, new Listener<RequestResult<Object>>() {

					@Override
					public void onResponse(RequestResult<Object> arg0) {
						dismissLoadingDialog();
						propmt.setVisibility(View.VISIBLE);
						propmt_detail.setText(Html.fromHtml(arg0.msg));
					}
				}, this,
				new TypeToken<RequestResult<AccountPropertyBean>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);
	}
	
	private void getDataFromNet(String userId) {
		// TODO Auto-generated method stub
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		FormResultRequest<AccountPropertyBean> getResultRequest = new FormResultRequest<AccountPropertyBean>(
				UrlConstants.GETUSERTOTALAMOUNT, new Listener<RequestResult<AccountPropertyBean>>() {

					@Override
					public void onResponse(RequestResult<AccountPropertyBean> arg0) {
						dismissLoadingDialog();
						if(arg0.flag == 1) {
							accountPropertyBean = arg0.getRs();
							totalAccount = accountPropertyBean.rechargeAmount-accountPropertyBean.withdrawAmount+accountPropertyBean.investRevenue-accountPropertyBean.revenueFeeAmount;
							warning();
						}
					}
				}, this,
				new TypeToken<RequestResult<AccountPropertyBean>>() {
				}.getType());
		getResultRequest.setRequestParams(ajaxParams);
		executeRequest(getResultRequest);
	}
	
	
	private void warning() {
		if(totalAccount > 0) {
			dialog = MMAlert.createShowCenterDialog(context, "温馨提示", "您当前的账户总资产大于0元，不能删除银行卡。请先将账户总资产提现后再进行删除操作", "取消", "确定", null, null);
		} else {
			dialog = MMAlert.createShowCenterDialog(context, "温馨提示", "您确定要删除该张银行卡吗？", "取消", "确定", null, new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					deleteBankCard(userId, bankCardBean.getCardId());
				}
			});
		}
		dialog.show();
	}

	private void checkInput() {
		if(chooseBean == null) {
			ToastMsg.showToastMsg(this, "请选择开户行");
			return ;
		} else if(card_number_detail_et.length() < 12) {
			ToastMsg.showToastMsg(this, "请填写12-19位的银行卡号");
			return ;
		} else if(GlobalApp.userModel.getIsSetPayPwd() == 0) {
			ToastMsg.showToastMsg(this, "您未设置交易密码，请前往设置");
			return;
		}
		else if(open_card_address_detail_et.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入交易密码");
			return;
		}
		
		addBankCard(userId, card_number_detail_et.getText().toString(),
				chooseBean.getId(), MD5Security.getMd5_32_UP(open_card_address_detail_et.getText().toString()));
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		if(arg0 == 100 && arg1 == 10000) {
			chooseBean = bankList.get(arg2.getIntExtra("position", 0));
			bank_name_detail.setText(chooseBean.getBankName());
		}
	}
	/**
	 * 
	 * @description：获取银行卡列表
	 * @author zc
	 * @date 2015年6月2日 下午5:38:24
	 */
	private void getBankList(String userId) {
//		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
//		ajaxParams.putCommonTypeParam("keyword", keyword);
//		ajaxParams.putCommonTypeParam("pageNo", pageNo);
//		ajaxParams.putCommonTypeParam("pageSize", pageSize);
		FormResultRequest<ArrayList<BankCardBean>> request = new FormResultRequest<ArrayList<BankCardBean>>(UrlConstants.GETBANKLIST, this, this, new TypeToken<RequestResult<ArrayList<BankCardBean>>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	/**
	 * 
	 * @description：删除银行卡
	 * @author zc
	 * @date 2015年6月2日 下午5:38:45
	 */
	private void deleteBankCard(String userId, String cardId) {
		showLoadingDialog("删除中");
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("cardId", cardId);
		FormResultRequest<Object> request = new FormResultRequest<Object>(UrlConstants.DELETEBANKCARD, new Listener<RequestResult<Object>>() {

			@Override
			public void onResponse(RequestResult<Object> arg0) {
				dismissLoadingDialog();
				if(arg0.flag == 1) {
					setResult(10000);
					finish();
				}
				
			}

		}, this, new TypeToken<RequestResult<Object>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	/**
	 * 
	 * @description：添加银行卡
	 * @author zc
	 * @date 2015年6月2日 下午5:40:40
	 */
	private void addBankCard(String userId, String cardNumber, String bankId, String payPwd) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("bankId", bankId);
		ajaxParams.putCommonTypeParam("cardNumber", cardNumber);
//		ajaxParams.putCommonTypeParam("realName", realName);
		ajaxParams.putCommonTypeParam("payPwd", payPwd);
		FormResultRequest<Object> request = new FormResultRequest<Object>(UrlConstants.ADDBANKCARD, new Listener<RequestResult<Object>>() {

			@Override
			public void onResponse(RequestResult<Object> arg0) {
				dismissLoadingDialog();
				if(arg0.flag == 1) {
					setResult(10000);
					finish();
				}
				ToastMsg.showToastMsg(BankInfoActivity.this, arg0.msg);
			}

		}, this, new TypeToken<RequestResult<Object>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	@Override
	public void onResponse(RequestResult<ArrayList<BankCardBean>> arg0) {
		if(arg0.flag == 1) { 
			
			if(arg0.getRs() != null && arg0.getRs().size() > 0) {
				bankList = arg0.getRs();
			}
		}
	}
	
	private String getHideRealName(String realName) {
		StringBuffer sb = new StringBuffer(realName.substring(0, 1));
		int count = realName.length() - 1;
		for(int i = 0; i < count; i++) {
			sb.append('*');
		}
		return sb.toString();
	}
	
	private String getHideIdCard(String idCard) {
		StringBuffer sb = new StringBuffer(idCard.substring(0, 4));
		int count = idCard.length() - 8;
		for(int i = 0; i < count; i++) {
			sb.append('*');
		}
		sb.append(idCard.substring(idCard.length() - 4));
		return sb.toString();
	}

}
